import requests
import json
import sys
import os

def load_config(config_file='config.json'):
    """Load configuration from JSON file"""
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Configuration file {config_file} not found!")
        sys.exit(1)
    except json.JSONDecodeError:
        print(f"Invalid JSON in configuration file {config_file}!")
        sys.exit(1)

def get_environment_config(config, env_name):
    """Get configuration for specified environment"""
    if env_name not in config:
        print(f"Environment '{env_name}' not found in configuration!")
        print(f"Available environments: {list(config.keys())}")
        sys.exit(1)
    return config[env_name]

def get_all_users(base_url, token):
    """Get all users from GitLab instance with pagination support"""
    all_users = []
    page = 1
    per_page = 100  # Maximum allowed per page
    
    headers = {'PRIVATE-TOKEN': token}
    
    while True:
        # API endpoint for users with pagination
        users_url = f'{base_url}/users?page={page}&per_page={per_page}'
        
        print(f"Fetching page {page}...")
        response = requests.get(users_url, headers=headers)
        
        if response.status_code != 200:
            print(f"Failed to fetch users: {response.status_code}")
            print(response.text)
            break
        
        users = response.json()
        
        # If no users returned, we've reached the end
        if not users:
            break
            
        all_users.extend(users)
        
        # Check if we got less than per_page, indicating last page
        if len(users) < per_page:
            break
            
        page += 1
    
    return all_users

def display_users(users, detailed=False):
    """Display user information"""
    print(f"\nTotal users found: {len(users)}")
    print("=" * 80)
    
    for i, user in enumerate(users, 1):
        if detailed:
            print(f"{i}. User Details:")
            print(f"   ID: {user.get('id', 'N/A')}")
            print(f"   Username: {user.get('username', 'N/A')}")
            print(f"   Name: {user.get('name', 'N/A')}")
            print(f"   Email: {user.get('email', 'N/A')}")
            print(f"   State: {user.get('state', 'N/A')}")
            print(f"   Created: {user.get('created_at', 'N/A')}")
            print(f"   Last Activity: {user.get('last_activity_on', 'N/A')}")
            print(f"   Admin: {user.get('is_admin', False)}")
            print(f"   External: {user.get('external', False)}")
            print(f"   Web URL: {user.get('web_url', 'N/A')}")
            print("-" * 60)
        else:
            # Simple format
            state = user.get('state', 'N/A')
            admin_flag = " [ADMIN]" if user.get('is_admin', False) else ""
            external_flag = " [EXTERNAL]" if user.get('external', False) else ""
            print(f"{i:3d}. {user.get('username', 'N/A'):20} | {user.get('name', 'N/A'):30} | {state:10}{admin_flag}{external_flag}")

def save_users_to_file(users, filename, env_name):
    """Save users data to JSON file"""
    output_data = {
        'environment': env_name,
        'total_users': len(users),
        'export_time': json.dumps(None, default=str),  # Will be replaced by current time
        'users': users
    }
    
    # Add current timestamp
    from datetime import datetime
    output_data['export_time'] = datetime.now().isoformat()
    
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(output_data, f, indent=2, ensure_ascii=False)
        print(f"\nUsers data saved to: {filename}")
    except Exception as e:
        print(f"Failed to save users data: {e}")

def main():
    # Get script directory to find config file
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_file = os.path.join(script_dir, 'config.json')
    
    # Load configuration
    config = load_config(config_file)
    
    # Determine which environment to use
    if len(sys.argv) > 1:
        env_name = sys.argv[1]
    else:
        # Default to 'local' if no argument provided
        env_name = 'local'
        print(f"No environment specified, using default: {env_name}")
        print(f"Available environments: {list(config.keys())}")
        print(f"Usage: python {os.path.basename(__file__)} <environment_name> [--detailed] [--save]")
        print()
    
    # Check for additional options
    detailed = '--detailed' in sys.argv
    save_to_file = '--save' in sys.argv
    
    # Get environment configuration
    env_config = get_environment_config(config, env_name)
    base_url = env_config['url']
    token = env_config['token']
    
    print(f"Using environment: {env_name}")
    print(f"API URL: {base_url}")
    print(f"Detailed output: {detailed}")
    print(f"Save to file: {save_to_file}")
    print()
    
    # Get all users
    try:
        users = get_all_users(base_url, token)
        
        if users:
            # Display users
            display_users(users, detailed)
            
            # Save to file if requested
            if save_to_file:
                filename = f"users_{env_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
                save_users_to_file(users, filename, env_name)
        else:
            print("No users found or failed to retrieve users.")
            
    except Exception as e:
        print(f"Error occurred: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
